#define _CRT_SECURE_NO_WARNINGS
#include "Slist.h"
void SLTPrint(SLTNode* phead) {
	SLTNode* pcur = phead;
	while (pcur) {
		printf("%d->", pcur->data);
		pcur = pcur->next;
	}
	printf("NULL\n");
}

SLTNode* SLTBuyNode(SLTDataType x) {
	SLTNode* newnode = (SLTNode*)malloc(sizeof(SLTNode));
	if (newnode == NULL) {
		perror("malloc fail!");
		exit(1);
	}
	newnode->next = NULL;
	newnode->data = x;

	return newnode;
}
void SLTPushBack(SLTNode** pphead, SLTDataType x) {
	assert(pphead);
	SLTNode* newnode = SLTBuyNode(x);
	if (*pphead == NULL) {
		*pphead = newnode;
	}else {
		SLTNode* pcur = *pphead;
		while (pcur->next)pcur = pcur->next;
		pcur->next = newnode;
	}
}

void SLTPushFront(SLTNode** pphead, SLTDataType x) {
	assert(pphead);
	SLTNode* newnode = SLTBuyNode(x);
	newnode->next = *pphead;
	*pphead = newnode;
}

void SLTPopBack(SLTNode** pphead) {
	assert(pphead && *pphead);
	if ((*pphead)->next == NULL) {
		free(*pphead);
		*pphead = NULL;
		return;
	}
	SLTNode* ptail = *pphead;
	SLTNode* pcur = ptail;
	while (ptail->next) {
		pcur = ptail;
		ptail = ptail->next;
	}

	pcur->next = NULL;
	free(ptail);
	ptail = NULL;
}

void SLTPopFront(SLTNode** pphead) {
	assert(pphead && *pphead);
	SLTNode* pcur = *pphead;
	*pphead = pcur->next;
	free(pcur);
}

SLTNode* SLTFind(SLTNode* phead, SLTDataType x) {
	SLTNode* pcur = phead;
	while (pcur) {
		if (pcur->data == x)return pcur;
		pcur = pcur->next;
	}
	return NULL;
}

void SLTInsert(SLTNode** pphead, SLTNode* pos, SLTDataType x) {
	assert(pphead && pos);
	SLTNode* pcur = *pphead;
	if (pos == pcur) {
		SLTPushFront(pphead, x);
	}
	else {
		SLTNode* newnode = SLTBuyNode(x);
		while (pcur->next && pcur->next != pos) {
			pcur = pcur->next;
		}
		newnode->next = pos;
		pcur->next = newnode;
	}
	
}

void SLTInsertAfter(SLTNode* pos, SLTDataType x) {
	assert(pos);
	SLTNode* newnode = SLTBuyNode(x);
	newnode->next = pos->next;
	pos->next = newnode;
}

void SLTErase(SLTNode** pphead, SLTNode* pos) {
	assert(pphead && pos);
	SLTNode* pcur = *pphead;
	if (pcur == pos) {
		SLTPopFront(pphead);
	}
	else {
		while (pcur->next && pcur->next != pos) {
			pcur = pcur->next;
		}
		pcur->next = pos->next;
		free(pos);
		pos = NULL;
	}
}

void SLTEraseAfter(SLTNode* pos) {
	assert(pos && pos->next);
	SLTNode* del = pos->next;
	pos->next = del->next;
	free(del);
	del = NULL;
}

void SListDestroy(SLTNode** pphead) {
	assert(pphead);
	SLTNode* pcur = *pphead;
	SLTNode* next = pcur;
	while (next) {
		next = pcur->next;
		free(pcur);
		pcur = next;
	}
	*pphead = NULL;
}